<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用户1 ID" prop="user1Id">
        <el-input
          v-model="queryParams.user1Id"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户2 ID" prop="user2Id">
        <el-input
          v-model="queryParams.user2Id"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关系状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" :value="1" />
          <el-option label="已拉黑" :value="2" />
          <el-option label="已删除" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:friendships:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:friendships:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:friendships:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:friendships:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="friendshipsList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="关系ID" align="center" prop="friendshipId" width="100" />
      <el-table-column label="用户1 ID" align="center" prop="user1Id" width="100" />
      <el-table-column label="用户2 ID" align="center" prop="user2Id" width="100" />
      <el-table-column label="关系状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success" size="small">正常</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="danger" size="small">已拉黑</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="info" size="small">已删除</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="备注名" align="center" prop="remark" min-width="120" show-overflow-tooltip />
      <el-table-column label="分组ID" align="center" prop="groupId" width="100" />
      <el-table-column label="亲密度" align="center" prop="intimacyScore" width="100">
        <template slot-scope="scope">
          <el-progress 
            v-if="scope.row.intimacyScore !== null && scope.row.intimacyScore !== undefined" 
            :percentage="Math.min(scope.row.intimacyScore, 100)" 
            :color="getIntimacyColor(scope.row.intimacyScore)"
            :stroke-width="8"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="最后互动" align="center" prop="lastInteraction" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastInteraction, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成为好友" align="center" prop="createdAt" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:friendships:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:friendships:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改好友关系对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="用户1 ID" prop="user1Id">
                  <el-input v-model="form.user1Id" placeholder="请输入用户1的ID" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="用户2 ID" prop="user2Id">
                  <el-input v-model="form.user2Id" placeholder="请输入用户2的ID" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="关系状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="2">已拉黑</el-radio>
                    <el-radio :label="3">已删除</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="好友备注名" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入好友备注名" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="好友分组ID" prop="groupId">
                  <el-input v-model="form.groupId" placeholder="请输入好友分组ID" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 亲密度信息 -->
          <el-tab-pane label="亲密度信息" name="intimacy">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="亲密度分数" prop="intimacyScore">
                  <el-slider 
                    v-model="form.intimacyScore" 
                    :min="0" 
                    :max="100"
                    show-input
                  />
                  <span class="form-tip">* 亲密度范围：0-100，数值越高表示关系越亲密</span>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="最后互动时间" prop="lastInteraction">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.lastInteraction"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择最后互动时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFriendships, getFriendships, delFriendships, addFriendships, updateFriendships } from "@/api/system/friendships";

export default {
  name: "Friendships",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      friendshipsList: [],
      title: "",
      open: false,
      activeTab: 'basic',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        user1Id: null,
        user2Id: null,
        status: null,
        remark: null,
        groupId: null,
        intimacyScore: null,
        lastInteraction: null,
        createdAt: null,
        updatedAt: null
      },
      form: {},
      rules: {
        user1Id: [
          { required: true, message: "用户1的ID不能为空", trigger: "blur" }
        ],
        user2Id: [
          { required: true, message: "用户2的ID不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 根据亲密度返回进度条颜色 */
    getIntimacyColor(score) {
      if (score >= 80) return '#67c23a';
      if (score >= 50) return '#e6a23c';
      return '#909399';
    },
    getList() {
      this.loading = true;
      listFriendships(this.queryParams).then(response => {
        this.friendshipsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        friendshipId: null,
        user1Id: null,
        user2Id: null,
        status: 1,
        remark: null,
        groupId: null,
        intimacyScore: 0,
        lastInteraction: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.friendshipId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.activeTab = 'basic';
      this.open = true;
      this.title = "添加好友关系";
    },
    handleUpdate(row) {
      this.reset();
      this.activeTab = 'basic';
      const friendshipId = row.friendshipId || this.ids
      getFriendships(friendshipId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改好友关系";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.friendshipId != null) {
            updateFriendships(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFriendships(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const friendshipIds = row.friendshipId || this.ids;
      this.$modal.confirm('是否确认删除好友关系编号为"' + friendshipIds + '"的数据项？').then(function() {
        return delFriendships(friendshipIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('system/friendships/export', {
        ...this.queryParams
      }, `friendships_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  display: block;
}

::v-deep .el-tabs--border-card {
  box-shadow: none;
}

::v-deep .el-tabs__content {
  padding: 20px;
}
</style>
